<template>
  <el-dialog
    :before-close="close" :title="id===null?'创建角色':'更新角色'" :visible.sync="visible" width="80%"
    @open="open"
  >
    <el-form ref="form" :rules="rules" :model="form">
      <el-form-item label="角色名称" prop="name" label-width="100px">
        <el-input v-model="form.name" placeholder="请输入角色名称"/>
      </el-form-item>
      <el-form-item label="角色说明" prop="comment" label-width="100px">
        <el-input v-model="form.comment" placeholder="请输入角色说明"/>
      </el-form-item>
      <el-form-item label="角色权限" prop="permissions" label-width="100px">
        <permission-select v-model="form.permissions"/>
      </el-form-item>
      <el-form-item label="角色用户" label-width="100px" prop="users">
        <user-multiple-select v-model="form.users"/>
      </el-form-item>
    </el-form>

    <div style="height: 30px">
      <el-button v-if="id" style="float:right;" type="primary" @click="updateRole">更新</el-button>
      <el-button v-else style="float:right;" type="primary" @click="createRole">创建</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {create, detail, update} from "@/api/system/role";
import PermissionSelect from "@/views/system/permission/nameSelect.vue";
import UserMultipleSelect from "@/views/system/user/userMultipleSelect";

export default {
  name: "CreateUpdateDialog",
  components: {UserMultipleSelect, PermissionSelect},
  props: {
    visible: {type: Boolean, default: false},
    id: {type: Number, default: null},
  },

  data() {
    return {
      form: {},
      rules: {
        name: [{required: true, message: '请输入角色名称', trigger: 'blur'}]
      }
    }
  },

  methods: {
    open() {
      if (this.id === null) {
        this.form = {}
      } else {
        this.detailRole()
      }
    },

    close() {
      this.$parent.createUpdateDialogVisible = false
    },

    createRole() {
      this.$refs.form.validate(valid => {
        if (valid) {
          create(this.form).then(() => {
            this.$message({type: 'success', message: '创建角色成功'})
            this.$parent.page()
            this.close()
          })
        }
      })
    },

    updateRole() {
      this.$refs.form.validate(valid => {
        if (valid) {
          update(this.form).then(() => {
            this.$message({type: 'success', message: '更新角色成功'})
            this.$parent.page()
            this.close()
          })
        }
      })
    },

    detailRole() {
      detail(this.id).then(res => {
        this.form = res.data
      })
    }
  }
}
</script>

<style scoped>

</style>
